package cn.wolfcode.postbar.web.controller;

import cn.wolfcode.postbar.annotation.RequiredLogin;
import cn.wolfcode.postbar.domain.UserInfo;
import cn.wolfcode.postbar.redis.service.IUserInfoRedisService;
import cn.wolfcode.postbar.service.IUserInfoService;
import cn.wolfcode.postbar.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@RestController
@RequestMapping("users")
public class UseInfoController {

    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

/*
    @PostMapping("/regist")
    public Object regist(String phone,String nickname,String password,String rpassword,String verifyCode){
       */
/* try {
            userInfoService.regist(phone,nickname,password,rpassword,verifyCode);
        }catch (LogicException le){
            //给用户看到的异常
            le.printStackTrace();
            //参数为null,不需要带上参数
            return JsonResult.error(JsonResult.CODE_ERROR_PARAM,le.getMessage(),null);
        }catch (Exception e){
            //出现问题: 程序系统出现的bug信息也显示用户看到,而系统要求,这类型的bug不能直接给用户看到
            //核心:如何区分主动抛出异常与系统异常,系统异常无法穷举,控制并识别主动抛出异常(自定义异常)
            //解决方法:
            e.printStackTrace();
            //参数为null,不需要带上参数
            return JsonResult.defaultError();
        }*//*

        userInfoService.regist(phone,nickname,password,rpassword,verifyCode);
        //返回jsonResult
        return JsonResult.success();
    }
*/

    @PostMapping("/login")
    public Object login(String username,String password){
        //登陆
        UserInfo user = userInfoService.login(username,password);
        //登陆成功,创建token,缓存user对象到redis中
        String token = userInfoRedisService.setToken(user);
        //user
        //token
        HashMap<String, Object> map = new HashMap<>();
        map.put("user",user);
        map.put("token",token);
        //返回jsonResult
        return JsonResult.success(map);
    }

    //获取当前登陆用户信息,前提: token 作为redis的key
    //如果没有等就进行拦截,提示需要登陆
    @RequiredLogin
    @GetMapping("/currentUser")
    public Object currentUser(HttpServletRequest request){
        //从请求头中获取token
        String token = request.getHeader("token");
        //以token获取用户对象
        UserInfo userInfo = userInfoRedisService.getUserByToken(token);
        return JsonResult.success(userInfo);
    }
}
